﻿using System;
using System.IO;
using System.Text;

using Yahoo.Yui.Compressor;

namespace ScriptXCompiler
{
    class FileOutput : IOutput
    {
        private StreamWriter _w;
        private StringBuilder _str;
        public FileOutput(string path, bool append)
        {
            _w = new StreamWriter(path, append);
            _str = new StringBuilder();
        }

        public void WriteWithIdent(int number, string str)
        {
            string s = new string(' ', number);
            _str.Append(s + str);
        }

        public void WriteWithIdent(int number, string fmt, params object[] args)
        {
            string s = new string(' ', number);
            _str.Append(s + string.Format(fmt, args));
        }

        public void WriteLineWithIdent(int number, string str)
        {
            string s = new string(' ', number);
            _str.AppendLine(s + str);
        }

        public void WriteLineWithIdent(int number, string fmt, params object[] args)
        {
            string s = new string(' ', number);
            _str.AppendLine(s + string.Format(fmt, args));
        }

        public void Write(string str)
        {
            _str.Append(str);
        }

        public void Write(string fmt, params object[] args)
        {
            _str.Append(string.Format(fmt, args));
        }

        public void WriteLine(string str)
        {
            _str.AppendLine(str);
        }

        public void WriteLine(string fmt, params object[] args)
        {
            _str.AppendLine(string.Format(fmt, args));
        }

        public void Flush()
        {
            _w.Write(_str.ToString());
            _str.Clear();
        }

        public void Compress()
        {
            string js = JavaScriptCompressor.Compress(_str.ToString());
            _str = new StringBuilder(js);
        }

        public void Dispose()
        {
            _w.Flush();
            _w.Dispose();
        }
    }
}
